package com.atguigu.controller;


import com.alibaba.fastjson.JSON;
import com.atguigu.entity.CartInfo;
import com.atguigu.entity.OrderDetail;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.UserAddress;
import com.atguigu.feign.CartFeignClient;
import com.atguigu.feign.UserFeignClient;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.AuthContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单明细表 前端控制器
 * </p>
 *
 * @author hachimen
 * @since 2021-09-07
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderInfoService orderInfoService;

    //1.订单确认信息
    @GetMapping("/confirm")
    public RetVal<Map<String, Object>> confirm(HttpServletRequest request) {
        //获取userid
        String userId = AuthContextHolder.getUserId(request);
        List<UserAddress> userAddressList = userFeignClient.queryAddressByUserId(userId);//*收货地址列表
        List<CartInfo> cartInfoList = cartFeignClient.getSelectedProduct(userId);//购物车列表

        List<OrderDetail> orderDetailList = new ArrayList<>();//*结账清单

        BigDecimal totalMoney = new BigDecimal(0);
        Integer totalNum = 0;
        for (CartInfo cartInfo : cartInfoList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setOrderPrice(cartInfo.getCartPrice());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum() + "");
            orderDetailList.add(orderDetail);
            totalMoney = totalMoney.add(cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
            totalNum += cartInfo.getSkuNum();
        }

        Map<String, Object> retMap = new HashMap<>();//定义返回数据
        retMap.put("userAddressList", userAddressList);
        retMap.put("detailArrayList", orderDetailList);
        retMap.put("totalMoney", totalMoney);
        retMap.put("totalNum", totalNum);
        String tradeNo = orderInfoService.generateTradeNo(userId);//生成流水号
        retMap.put("tradeNo", tradeNo);
        return RetVal.ok(retMap);
    }

    //2.提交订单
    @PostMapping("/submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
        String tradeNo = request.getParameter("tradeNo");
        String userId = AuthContextHolder.getUserId(request);
        //验证流水号
        Boolean flag = orderInfoService.checkTradeNo(tradeNo, userId);
        if (!flag) {
            return RetVal.fail().message("请勿重复提交订单");
        }
        orderInfoService.deleteTradeNo(tradeNo, userId);//删除流水号
        //验证价格和库存
        List<String> warningMsgList = orderInfoService.checkStockAndPrice(orderInfo, userId);
        if (warningMsgList.size() > 0) {
            return RetVal.fail().message(StringUtils.join(warningMsgList, ","));
        }
        //提交订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrderAndDetail(orderInfo, userId);
        return RetVal.ok(orderId);
    }

    //3.根据订单id获取订单信息
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId) {
        return orderInfoService.getOrderInfo(orderId);
    }

    //4.拆单
    @RequestMapping("/splitOrder")
    public String splitOrder(@RequestParam Long orderId,@RequestParam String wareHouseIdSkuIdMap,HttpServletRequest request) {
        //数据格式 [{"wareHouseId":"1","skuIdList":["18","19"]},{"wareHouseId":"2","skuIdList":["30"]}]
        List<Map<String, Object>> childOrderList = orderInfoService.spiltOrder(orderId, wareHouseIdSkuIdMap);
        return JSON.toJSONString(childOrderList);
    }

    //5.给秒杀提供的提交订单数据接口
    @PostMapping("/saveSeckillOrder")
    public Long saveSeckillOrder(@RequestBody OrderInfo orderInfo){
        return orderInfoService.saveOrderAndDetail(orderInfo,"999");
    }
}

